package com.resou.reader.search.search2;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.resou.reader.R;
import com.resou.reader.activity.freebook.FreeBookActivity;
import com.resou.reader.api.entry.SearchBean;
import com.resou.reader.bookshelf.readhistory.datasupport.SearchHistory;
import com.resou.reader.bookstore.freezone.FreezoneActivity;
import com.resou.reader.search.SearchPresenter;
import com.resou.reader.search.adpter.SearchKeyWordAdapter;
import com.resou.reader.utils.ToastUtil;
import com.resou.reader.view.FlowLayout;
import com.resou.reader.view.NetErrorFragment;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.umeng.socialize.utils.ContextUtil.getContext;

public class Search2Activity extends AppCompatActivity {


    public static void start(Context context) {
        Intent starter = new Intent(context, Search2Activity.class);
//    starter.putExtra();
        context.startActivity(starter);
    }


    @BindView(R.id.tv_input_frame)
    EditText tvInputFrame;
    @BindView(R.id.iv_clear)
    ImageView ivClear;
    @BindView(R.id.search_layout)
    LinearLayout searchLayout;
    @BindView(R.id.tv_cancel)
    TextView tvCancel;
    @BindView(R.id.ll_searchBar_container)
    LinearLayout llSearchBarContainer;
    @BindView(R.id.no_search_result_layout)
    LinearLayout noSearchResultLayout;
    @BindView(R.id.tv_people_search)
    TextView tvPeopleSearch;
    @BindView(R.id.tv_search_history)
    TextView tvSearchHistory;
    @BindView(R.id.tv_delete)
    TextView tvDelete;
    @BindView(R.id.rv_search_history)
    RecyclerView rvSearchHistory;
    @BindView(R.id.rv_search_result)
    RecyclerView rvSearchResult;
    @BindView(R.id.llSearchKeyContent)
    LinearLayout llSearchKeyContent;//智能提示的搜索提示语容器
    @BindView(R.id.tvSearchHint)
    TextView tvSearchHint;//智能提示的搜索提示与文本
    @BindView(R.id.rvKeyWord)
    RecyclerView rvKeyWord; //显示智能搜索的关键字列表控件
    @BindView(R.id.rlFreeOnclick)
    RelativeLayout rlFreeOnclick;//免费专区点击时间
    @BindView(R.id.llSearchResult)
    LinearLayout llSearchResult;//搜索结果的容器
    boolean isLoadingMore = false;
    @BindView(R.id.flow_layout)
    FlowLayout flowLayout;
    @BindView(R.id.ll_flowLayout_container)
    LinearLayout llFlowLayoutContainer;
    @BindView(R.id.fl_hot_word_container)
    FrameLayout flHotWordContainer;
    @BindView(R.id.fl_search_history_container)
    FrameLayout flSearchHistoryContainer;
    @BindView(R.id.fl_content)
    FrameLayout flContent;
    boolean isEndLength = false;
    private NetErrorFragment mNetErrorFragment;
    boolean isRefreshShow = true;//用户点击历史记录与标签是  输入框值变化 导致页面渲染 成智能推荐页面
    private Search2Presenter mPresenter;
    private SearchResultAdapter mSearchResultAdapter;
    private SearchHistoryAdapter mSearchHistoryAdapter;
    private SearchKeyWordAdapter mSearchKeyWordAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search2);
        ButterKnife.bind(this);
        initPresenter();
        initRecyclerView();
        initInputBox();
        initHotWords();
        initSearchHistory();

    }

    private void initPresenter() {
        mPresenter = new Search2Presenter(this);
        mSearchKeyWordAdapter = new SearchKeyWordAdapter(R.layout.adapter_search_keyword);
    }


    private void initInputBox() {
        //给输入框设置键盘的监听器
        tvInputFrame.setOnKeyListener((v, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                // 先隐藏键盘
                hideKeyBorad();
                //进行搜索操作的方法，在该方法中可以加入mEditSearchUser的非空判断
                if (!TextUtils.isEmpty(tvInputFrame.getText().toString())) {
                    showType(2);
                    mPresenter.search(tvInputFrame.getText().toString());
                }
            }
            return false;
        });
        tvInputFrame.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                Log.e(TAG, "showSearchResult: " + isRefreshShow);
                tvInputFrame.requestFocus();
                if (s.length() == 0) {
                    ivClear.setImageResource(R.mipmap.ic_search);
                    showType(0);
                    if (mSearchResultAdapter != null) {
                        mSearchResultAdapter.clear();
                        rvSearchResult.scrollToPosition(0);
                    }
                } else {
                    ivClear.setImageResource(R.mipmap.ic_clear);
                    if (isEndLength) {
                        tvInputFrame.setSelection(s.length());//移动光标到最后
                        isEndLength = false;
                    }
                    if (isRefreshShow) {
                        tvSearchHint.setText(tvInputFrame.getText().toString());
                        mPresenter.searchKeyWord(tvInputFrame.getText().toString() + "");
                    } else {
                        mPresenter.search(tvInputFrame.getText().toString() + "");
                        isRefreshShow = true;

                    }
                }
            }
        });
    }

    private static final String TAG = "Search2Activity-APP";

    private void initHotWords() {
        mPresenter.getHotWord();
    }

    private void initSearchHistory() {
        mPresenter.getAllHistory();
    }

    private void initRecyclerView() {
        //搜索结果
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        rvSearchResult.setLayoutManager(layoutManager);
        mSearchResultAdapter = new SearchResultAdapter(this);
        rvSearchResult.setAdapter(mSearchResultAdapter);
        /**
         * 关键字搜索
         */
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        rvKeyWord.setLayoutManager(linearLayoutManager);
        mSearchKeyWordAdapter = new SearchKeyWordAdapter(R.layout.adapter_search_keyword, null, "");
        rvKeyWord.setAdapter(mSearchKeyWordAdapter);
        /**
         * 智能关键字结果列表点击的回调
         */
        mSearchKeyWordAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                SearchBean searchBean = (SearchBean) adapter.getData().get(position);
                switch (view.getId()) {
                    case R.id.llOnclick:
                        isRefreshShow = false;
                        isEndLength = true;
                        tvInputFrame.setText(searchBean.getNovelName() + "");
                        // 先隐藏键盘
                        hideKeyBorad();
                        //进行搜索操作的方法，在该方法中可以加入mEditSearchUser的非空判断
                        mPresenter.search(searchBean.getNovelName() + "");
                        break;
                }
            }
        });

        //给搜索结果recyclerView设置滚动监听器，用于加载下一章
        rvSearchResult.setHasFixedSize(true);
        rvSearchResult.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastVisibleItem = layoutManager.findLastVisibleItemPosition();
                int totalItemCount = layoutManager.getItemCount();
                if (lastVisibleItem >= totalItemCount - 2 && dy > 0) {  //还剩2个Item时加载更多
                    if (!isLoadingMore) {
                        isLoadingMore = true;
                        mPresenter.searchNext(tvInputFrame.getText().toString());
                    }
                }
            }
        });
        //搜索历史
        rvSearchHistory.setLayoutManager(new LinearLayoutManager(this));
        mSearchHistoryAdapter = new SearchHistoryAdapter();
        mSearchHistoryAdapter.setInteractionListener(text -> {
            isEndLength = true;
            isRefreshShow = false;
            showType(2);
            tvInputFrame.setText(text);
            mPresenter.search(text);
        });
        rvSearchHistory.setAdapter(mSearchHistoryAdapter);
    }

    /**
     * 显示关键字
     *
     * @param data
     */
    public void showHotWord(List<String> data) {
        flowLayout.removeAllViews();
        List<String> assignList = getAssignList(data);
//        assignList.add("免费专区");
        for (int k = 0; k < assignList.size(); k++) {
            TextView tv = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.hot_text_item, flowLayout, false);
            tv.setText(assignList.get(k));
            tv.setOnClickListener(v -> {
                isEndLength = true;
                isRefreshShow = false;
                String str = ((TextView) v).getText().toString();
                if (str.equals("免费专区")) {
                    FreezoneActivity.start(this);
                } else {
                    showType(2);
                    tvInputFrame.setText(str);
                    mPresenter.search(str);
                }
            });
            flowLayout.addView(tv);
        }
    }

    public void showError(Throwable throwable) {
        ToastUtil.makeShortToast("网络异常");
        showNetErrorView(R.id.fl_content);
    }

    public void showHistorySearch(List<SearchHistory> searchHistories) {
        if (searchHistories == null || searchHistories.size() == 0) {
            mSearchHistoryAdapter.clear();
        } else {
            mSearchHistoryAdapter.setSearchHistories(searchHistories);
        }
    }

    public void showHotAndHistory() {
        mPresenter.getAllHistory();
    }

    public void showSearchResult(List<SearchBean> data, String query) {
        if (data == null || data.size() == 0) {
//            isRefreshShow = false;
            showType(3);
            mSearchResultAdapter.setList(null, query);
        } else {
            showType(2);
            mSearchResultAdapter.setList(data, query);
        }
    }

    /**
     * 搜索关键字
     *
     * @param data
     * @param query
     */
    public void showKeyWordResult(List<SearchBean> data, String query) {
        showType(1);
        mSearchKeyWordAdapter.setData(data, query);
    }


    public void addSearchResult(List<SearchBean> data, String query) {
        mSearchResultAdapter.addList(data, query);
        isLoadingMore = false;
    }

    private static int start = 0;

    //从第start位置取
    private List<String> getAssignList(List<String> list) {
        if (list.size() <= SearchPresenter.HOT_SIZE_MAX) {
            return list;
        }
        List<String> result = new ArrayList<>();
        if (start >= list.size()) {
            start -= list.size();
        }
        while (result.size() < SearchPresenter.HOT_SIZE_MAX) {
            if (start == list.size()) {
                start = 0;
            }
            result.add(list.get(start));
            start++;
        }
        return result;
    }

    @OnClick({R.id.iv_clear, R.id.tv_cancel, R.id.tv_delete, R.id.rlFreeOnclick})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_clear:
                //清空输入框
                tvInputFrame.setText("");
                showHotAndHistory();
                break;
            case R.id.tv_cancel:
                finish();
                break;

            case R.id.tv_delete:
                mPresenter.deleteAllHistory();
                mPresenter.getAllHistory();
                break;
            case R.id.rlFreeOnclick:
                FreezoneActivity.start(this);
                break;
        }
    }

    /**
     * @param type 0：显示推荐标签   1:显示智能推荐；2：显示结果 ；3显示空页面
     */
    public void showType(int type) {
        Log.i(TAG, "showType: " + type);
        switch (type) {
            case 0:
                /**
                 * 显示推荐标签 及历史记录
                 */
                flContent.setVisibility(View.VISIBLE);
                llSearchResult.setVisibility(View.GONE);
                llSearchKeyContent.setVisibility(View.GONE);
                noSearchResultLayout.setVisibility(View.GONE);
                break;
            case 1:
                /**
                 * 显示智能推荐标签
                 */
                flContent.setVisibility(View.GONE);
                llSearchKeyContent.setVisibility(View.VISIBLE);
                llSearchResult.setVisibility(View.GONE);
                noSearchResultLayout.setVisibility(View.GONE);
                break;
            case 2:
                /**
                 * 显示搜索结果
                 */
                llSearchResult.setVisibility(View.VISIBLE);
                llSearchKeyContent.setVisibility(View.GONE);
                noSearchResultLayout.setVisibility(View.GONE);
                rlFreeOnclick.setVisibility(View.GONE);
                flContent.setVisibility(View.GONE);
                if (tvInputFrame.getText().toString().length() == 0) {
                    return;
                }
                if ("免费专区".contains(tvInputFrame.getText().toString())) {
                    rlFreeOnclick.setVisibility(View.VISIBLE);
                }
                break;
            case 3:
                /**
                 * 显示无数据
                 */
                flContent.setVisibility(View.GONE);
                llSearchResult.setVisibility(View.GONE);
                llSearchKeyContent.setVisibility(View.GONE);
                noSearchResultLayout.setVisibility(View.VISIBLE);
                if ("免费专区".contains(tvInputFrame.getText().toString())) {
                    rlFreeOnclick.setVisibility(View.VISIBLE);
                    llSearchResult.setVisibility(View.VISIBLE);
                } else {
                    rlFreeOnclick.setVisibility(View.GONE);
                }

                break;

        }
    }

    /**
     * 键盘隐藏
     */
    private void hideKeyBorad() {
        // 先隐藏键盘
        ((InputMethodManager) Objects.requireNonNull(getSystemService(INPUT_METHOD_SERVICE)))
                .hideSoftInputFromWindow(Objects.requireNonNull(Search2Activity.this.getCurrentFocus())
                        .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 显示网络异常视图
     *
     * @param resId
     */
    public void showNetErrorView(int resId) {
        if (mNetErrorFragment == null) {
            mNetErrorFragment = new NetErrorFragment(new NetErrorFragment.OnClick() {
                @Override
                public void onClick() {
                    initHotWords();
                    initSearchHistory();
                    dismissNetErrorView();
                }
            });
        }
        mNetErrorFragment.show(resId, getSupportFragmentManager());
    }

    /**
     * 关闭无网络页码
     */
    public void dismissNetErrorView() {
        if (mNetErrorFragment != null) {
            mNetErrorFragment.dismiss();
        }
    }

}
